package com.kaplan.hackathon.dynamodb;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
import com.amazonaws.services.dynamodbv2.model.PutItemResult;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.model.TableDescription;

import com.kaplan.hackathon.LearningPodService;
import com.kaplan.hackathon.models.CatalogItem;
import com.kaplan.hackathon.models.QuestionResponse;
import com.kaplan.hackathon.models.User;

public class DynamoDBPersistence {
	private String accessKeyID = "AKIAIH3BU2XRQZ2MAE4A";
	private String secretAccessKey = "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";
	
	private static final Log log = LogFactory.getLog(DynamoDBPersistence.class);
	
	
	
	public void saveOrUpdateUser(User user) {
		AmazonDynamoDBClient instance;
        instance = DynamoDBClient.getInstance();        
        DynamoDBMapper mapper = new DynamoDBMapper(instance);
        mapper.save(user);
	}
	
	public void saveResponseOperation(QuestionResponse response) {
		AmazonDynamoDBClient instance;
        instance = DynamoDBClient.getInstance();        
        DynamoDBMapper mapper = new DynamoDBMapper(instance);
        mapper.save(response);
	}
	
	
	public void testCRUDOperations() {
		
		AmazonDynamoDBClient instance;
		
        instance = DynamoDBClient.getInstance();
        
        String tableName = "ProductCatalog2";
        
        //create table
        /*
        CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("name").withAttributeType(ScalarAttributeType.S))
                .withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
            TableDescription createdTableDescription = instance.createTable(createTableRequest).getTableDescription();
            System.out.println("Created Table: " + createdTableDescription);
        */
        /*
        Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James", "Sara");
        PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
        PutItemResult putItemResult = instance.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);

        // Add another item
        item = newItem("Airplane", 1980, "*****", "James", "Billy Bob");
        putItemRequest = new PutItemRequest(tableName, item);
        putItemResult = instance.putItem(putItemRequest);
        System.out.println("Result: " + putItemResult);
        */
        
        CatalogItem item = new CatalogItem();
        item.setId(201);
        item.setTitle("Kaplan");
        item.setISBN("611-11111");
        
        DynamoDBMapper mapper = new DynamoDBMapper(instance);
        mapper.save(item);
        
        
        // Retrieve the item.
        CatalogItem itemRetrieved = mapper.load(CatalogItem.class, 201);
        log.info("Item retrieved:");
        log.info(itemRetrieved);

        // Update the item.
        itemRetrieved.setISBN("622-2222222222");
         mapper.save(itemRetrieved);
        log.info("Item updated:");
        log.info(itemRetrieved);
        
        // Retrieve the updated item.
        DynamoDBMapperConfig config = new DynamoDBMapperConfig(DynamoDBMapperConfig.ConsistentReads.CONSISTENT);
        CatalogItem updatedItem = mapper.load(CatalogItem.class, 201, config);
        log.info("Retrieved the previously updated item:");
        log.info(updatedItem);
        
        // Delete the item.
        mapper.delete(updatedItem);
        
        // Try to retrieve deleted item.
        CatalogItem deletedItem = mapper.load(CatalogItem.class, updatedItem.getId(), config);
        if (deletedItem == null) {
           log.info("Done - Sample item is deleted.");
        }
        
	}
	
	private static Map<String, AttributeValue> newItem(String name, int year, String rating, String... fans) {
        Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
        item.put("name", new AttributeValue(name));
        item.put("year", new AttributeValue().withN(Integer.toString(year)));
        item.put("rating", new AttributeValue(rating));
        item.put("fans", new AttributeValue().withSS(fans));

        return item;
    }
}
